package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.entity.Category;
import com.demo.youxuanmall.mapper.CategoryMapper;
import com.demo.youxuanmall.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> listAll() {
        // 查询所有未删除的分类，按排序升序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getIsDeleted, 0)
               .orderByAsc(Category::getSort);
        return list(wrapper);
    }

    @Override
    @Transactional
    public void add(Category category) {
        // 设置默认值
        if (category.getSort() == null) {
            category.setSort(0);
        }
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        category.setIsDeleted(0);
        
        save(category);
    }

    @Override
    @Transactional
    public void update(Category category) {
        // 检查是否存在
        Category oldCategory = getById(category.getId());
        if (oldCategory == null) {
            throw new RuntimeException("分类不存在");
        }
        
        updateById(category);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 检查是否存在
        Category category = getById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        
        // 软删除
        category.setIsDeleted(1);
        updateById(category);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        // 检查是否存在
        Category category = getById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        
        // 更新状态
        category.setStatus(status);
        updateById(category);
    }

    @Override
    public List<Category> listEnabledCategories() {
        // 查询所有启用且未删除的分类，按排序升序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getStatus, 1)
               .eq(Category::getIsDeleted, 0)
               .orderByAsc(Category::getSort);
        return list(wrapper);
    }
} 